<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>数据库文档中心</title>
    <script src="js/marked.min.js"></script>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --hover-color: #f0f8ff;
            --border-color: #ecf0f1;
            --shadow-color: rgba(0,0,0,0.1);
        }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
            background: #f8f9fa;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 350px;
            background: white;
            box-shadow: 2px 0 8px var(--shadow-color);
            padding: 20px 0;
            overflow-y: auto;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
        }

        /* 主内容区 */
        .content {
            flex: 1;
            background: white;
            overflow-y: auto;
            padding: 40px 20px;
            position: relative;
        }

        /* 文档列表样式 */
        .doc-list {
            padding: 0 15px;
            flex: 1;
        }

        .doc-item {
            padding: 12px 20px;
            margin: 6px 0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            color: var(--primary-color);
            display: flex;
            align-items: center;
        }

        .doc-item:hover {
            background: var(--hover-color);
            transform: translateX(4px);
        }

        .doc-item.active {
            background: var(--secondary-color);
            color: white;
            font-weight: 500;
        }

        .doc-item::before {
            content: '📄';
            margin-right: 12px;
            font-size: 1.1em;
        }

        /* 搜索框 */
        .search-box {
            padding: 0 15px 15px;
            position: sticky;
            top: 0;
            background: white;
            z-index: 10;
        }

        .search-input {
            width: 90%;
            padding: 10px 15px;
            border: 2px solid var(--border-color);
            border-radius: 25px;
            font-size: 14px;
        }

        .search-input:focus {
            outline: none;
            border-color: var(--secondary-color);
            box-shadow: 0 0 8px rgba(52,152,219,0.2);
        }

        /* 加载动画 */
        .loader {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid var(--secondary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Markdown内容样式 */
        #docContent {
            line-height: 1.7;
            max-width: 60%;
            margin: 0 auto;
        }

        #docContent pre {
            background: #f4f4f4;
            padding: 15px;
            border-radius: 6px;
            overflow-x: auto;
        }

        #docContent h1,
        #docContent h2,
        #docContent h3,
        #docContent h4 {
            border-left: 4px solid var(--secondary-color);
            padding-left: 15px;
            margin-top: 1.8em;
        }

        #docContent table {
            border-collapse: collapse;
            width: 100%;
            margin: 25px 0;
            box-shadow: 0 1px 3px var(--shadow-color);
        }

        #docContent th,
        #docContent td {
            border: 1px solid var(--border-color);
            padding: 12px;
            text-align: left;
        }

        #docContent th {
            background-color: var(--secondary-color);
            color: white;
            word-break: keep-all;
        }

        #docContent tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        /* 生成按钮区域 */
        .generate-box {
            padding: 15px;
        }

        .generate-btn {
            width: 100%;
            padding: 12px;
            background: var(--secondary-color);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .generate-btn:hover {
            background: #2980b9;
        }

        .update-status {
            font-size: 0.9em;
            color: #7f8c8d;
            margin-top: 8px;
            text-align: center;
        }

        /* 返回顶部按钮 */
        .back-to-top {
            position: fixed;
            bottom: 40px;
            right: 40px;
            width: 45px;
            height: 45px;
            background: var(--secondary-color);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            opacity: 0;
            transition: all 0.3s;
            box-shadow: 0 4px 12px var(--shadow-color);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .back-to-top.show {
            opacity: 1;
        }

        .back-to-top:hover {
            background: #2980b9;
            transform: translateY(-3px);
        }

        .title {
            font-size: 1.2em;
            margin-bottom: 10px;
            color: var(--primary-color);
            font-weight: 500;
        }
    </style>
</head>
<body>
<div class="sidebar">
    <div class="generate-box">
        <div class="title">数据来源于: 10.0.2.40:6446</div>
        <button class="generate-btn" id="generateBtn">🔄 更新文档 <span id="lastGenerateTime"></span></button>
        <div class="update-status" id="updateStatus"></div>
    </div>
    <div class="search-box">
        <input type="text" class="search-input" placeholder="搜索文档..." id="searchInput" />
    </div>
    <ul class="doc-list" id="documents"></ul>
    <div class="loader" id="loader" style="display: none;"></div>
</div>

<div class="content">
    <div id="docContent"></div>
</div>

<!-- 返回顶部按钮 -->
<button class="back-to-top" id="backToTop" title="返回顶部">↑</button>

<script>
    class DocumentViewer {
        constructor() {
            this.currentDoc = null;
            this.docCache = new Map();
            this.init();
        }

        async init() {
            this.bindEvents();
            await this.loadDocumentList();
            await this.loadLastGenerateTime();
            document.getElementById('searchInput').focus();
            this.setupBackToTop();
        }

        setupBackToTop() {
            const backButton = document.getElementById('backToTop');
            const contentArea = document.querySelector('.content'); // 获取内容区域

            // 监听内容区域的滚动事件
            contentArea.addEventListener('scroll', () => {
                // 使用内容区域自身的scrollTop
                if (contentArea.scrollTop > 200) {
                    backButton.classList.add('show');
                } else {
                    backButton.classList.remove('show');
                }
            });

            backButton.addEventListener('click', () => {
                // 滚动内容区域到顶部
                contentArea.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        }

        bindEvents() {
            // 新增生成按钮事件
            document.getElementById('generateBtn').addEventListener('click', async () => {
                const btn = document.getElementById('generateBtn');
                btn.disabled = true;
                btn.innerHTML = '⏳ 生成中...';

                try {
                    const res = await fetch('/api/generate', { method: 'POST' });
                    if (!res.ok) throw new Error('生成请求失败');
                    alert('文档生成已开始，请稍后刷新查看最新文档');
                } catch (e) {
                    alert('生成失败: ' + e.message);
                } finally {
                    btn.disabled = false;
                    btn.innerHTML = '🔄 更新文档';
                }
            });

            document.getElementById('searchInput').addEventListener('input', e =>
                this.filterDocuments(e.target.value)
            );
        }

        async loadDocumentList() {
            try {
                const res = await fetch('/api/documents');
                if (!res.ok) throw new Error('无法加载文档列表');
                this.documents = await res.json();
                this.renderList(this.documents);
                if (this.documents.length) this.loadDocument(this.documents[0]);
            } catch (e) {
                this.showError('加载文档列表失败', e);
            }
        }

        async loadLastGenerateTime(){
            try {
                const res = await fetch('/api/lastGenerateTime');
                if (!res.ok) throw new Error('获取更新时间异常');
                const data = await res.json();
                document.getElementById('generateBtn').innerText  = `更新时间：${data.lastGenerateTime}`;
            } catch (e) {
                this.showError('加载文档列表失败', e);
            }
        }

        renderList(docs) {
            const list = document.getElementById('documents');
            list.innerHTML = docs.map(doc => `
                <li class="doc-item" data-file="${doc}">${doc.replace('_数据库设计文档_1.0.0.md', '')}</li>
            `).join('');

            list.querySelectorAll('.doc-item').forEach(item => {
                item.addEventListener('click', () => {
                    if (this.currentDoc === item.dataset.file) return;
                    document.querySelectorAll('.doc-item').forEach(i => i.classList.remove('active'));
                    item.classList.add('active');
                    this.loadDocument(item.dataset.file);
                });
            });
        }

        async loadDocument(filename) {
            if (this.currentDoc === filename) return;
            this.currentDoc = filename;
            this.showLoader();

            try {
                let content;
                if (this.docCache.has(filename)) {
                    content = this.docCache.get(filename);
                } else {
                    const res = await fetch(`/api/document/${encodeURIComponent(filename)}`);
                    if (!res.ok) throw new Error(`加载文档失败: ${filename}`);
                    content = await res.text();
                    this.docCache.set(filename, content);
                }

                const html = marked.parse(content);
                document.getElementById('docContent').innerHTML = html;

                if (location.hash) {
                    const anchor = document.querySelector(location.hash);
                    if (anchor) anchor.scrollIntoView({ behavior: 'smooth' });
                }

                const contentArea = document.querySelector('.content'); // 获取内容区域
                contentArea.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            } catch (e) {
                this.showError(`加载文档失败: ${filename}`, e);
            } finally {
                this.hideLoader();
            }
        }

        filterDocuments(keyword) {
            const filtered = this.documents.filter(doc =>
                doc.toLowerCase().includes(keyword.toLowerCase())
            );
            this.renderList(filtered);
        }

        showLoader() {
            document.getElementById('loader').style.display = 'block';
        }

        hideLoader() {
            document.getElementById('loader').style.display = 'none';
        }

        showError(title, error) {
            document.getElementById('docContent').innerHTML = `
                <h3 style="color: #dc3545;">${title}</h3>
                <p>${error.message}</p>
            `;
            console.error(title, error);
        }
    }

    document.addEventListener('DOMContentLoaded', () => new DocumentViewer());
</script>
</body>
</html>